package com.liuchuanzheng.lcz_wanandroid.module.user.viewmodel

import androidx.lifecycle.MutableLiveData
import com.jeremyliao.liveeventbus.LiveEventBus
import com.liuchuanzheng.lcz_wanandroid.R
import com.liuchuanzheng.lcz_wanandroid.base.BaseViewModel
import com.liuchuanzheng.lcz_wanandroid.ext.showToast
import com.liuchuanzheng.lcz_wanandroid.module.common.bus.LoginStatusEvent
import com.liuchuanzheng.lcz_wanandroid.module.user.UserManager
import com.liuchuanzheng.lcz_wanandroid.module.user.repository.UserRepository

/**
 * @author 刘传政
 * @date 2021/9/14 0014 18:20
 * QQ:1052374416
 * 电话:18501231486
 * 作用:
 * 注意事项:
 */
class LoginViewModel : BaseViewModel() {
    val userRepository by lazy { UserRepository() }


    //<editor-fold defaultstate="collapsed" desc="被外部观察的变量">
    // 上下两个标签包起来,是为了让它默认收起,并且在structure窗口查看是,有中文提示,
    // 并且结构整洁.并且此标签可以多层次嵌套,让你随心设置代码结构.此处只是为了试验效果.
    // 你可以用到你自己想用的地方
    val liveData_loginResult = MutableLiveData<Boolean>()
    val liveData_loading = MutableLiveData<Boolean>()
    //</editor-fold>

    fun login(username: String, password: String) {
        liveData_loading.value = true
        launch(
            workBlock = {
                var result = userRepository.login(username, password)
                handleResult(result,
                    successBlock = {
                        UserManager.updateUserInfo(result.data)
                        liveData_loginResult.value = true
                        showToast("登录成功")
                        val event = LoginStatusEvent().apply {
                            isLogin = true
                        }
                        LiveEventBus.get(LoginStatusEvent::class.java).post(event)
                    },
                    failBlock = {
                        liveData_loginResult.value = false
                        showToast("${result.errorMsg}")
                    }
                )
            }, errorBlock = {
                showToast(R.string.network_not_available)
            }, finillyBlock = {
                liveData_loading.value = false
            }
        )
    }
}